1851E - Nastya and Potions - CodeForces Solution


dfs and similar dp graphs greedy shortest paths

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define s second
#define f first
#define fastio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define V vector<ll>
#define VV vector<vector<ll>>
vector<ll> adj[200005+2];
ll cost[200005+2],ans[200005];

void dfs(ll p)
{
    if(ans[p]!=-1)return ;
    ll sum=0;
    for (auto u : adj[p])
    {
        dfs(u);
        sum+=ans[u];
    }
    if(adj[p].empty())ans[p]=cost[p];
    else ans[p]=min(sum,cost[p]);

}
int main()
{
   ll t=1;
   cin>>t;
    while(t--){
     ll n,k;
     cin>>n>>k;

     for(int i=1;i<=n;i++){cin>>cost[i];adj[i].clear();ans[i]=-1;}
     for(int i=1;i<=k;i++){ll x; cin>>x; cost[x]=0;}
     for(int i=1;i<=n;i++)
     {
         ll num;
         cin>>num;
         while(num--)
         {
             ll x;
             cin>>x;
             adj[i].pb(x);
         }
     }
     for(int i=1;i<=n;i++)dfs(i);
     for(int i=1;i<=n;i++)cout<<ans[i]<<" ";
     cout<<endl;
}
    return 0;
}


Comments

Submit
0 Comments
More Questions

152A - Marks
1398A - Bad Triangle
137A - Postcards and photos
1674D - A-B-C Sort
334A - Candy Bags
855A - Tom Riddle's Diary
1417A - Copy-paste
1038A - Equality
1061A - Coins
1676E - Eating Queries
1447A - Add Candies
1721D - Maximum AND
363C - Fixing Typos
1401A - Distance and Axis
658A - Bear and Reverse Radewoosh
1721E - Prefix Function Queries
977E - Cyclic Components
1140D - Minimum Triangulation
75C - Modified GCD
1722A - Spell Check
1722B - Colourblindness
1722D - Line
1722C - Word Game
1722G - Even-Odd XOR
552E - Vanya and Brackets
933A - A Twisty Movement
1722F - L-shapes
1196B - Odd Sum Segments
1325D - Ehab the Xorcist
552B - Vanya and Books